package models

import (
	"crypto/md5"
	"fmt"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"io"
	"public_security/tools"
	"strings"
)

const CtxLoginUser = "user"

type Users struct {
	BaseModel
	Id       int    `gorm:"primary_key"`
	Account  string `gorm:"type:varchar(50);not null;index" description:"账号"`
	Password string `gorm:"type:varchar(50);not null;index" description:"密码"`
	Name     string `gorm:"type:varchar(50);not null;index" description:"名称"`
	Token    string `gorm:"type:varchar(255);null"`
}

// 用户获取Token
func (i *Users) GetToken() string {
	auth := tools.NewAuthTool()
	token := auth.GenToken(map[string]interface{}{
		"id": i.Id,
	})
	return token
}
func AttachTokenToCookies(i *Users, ctxs ...*context.Context) {
	if len(ctxs) > 0 {
		if getRequestAgentType(ctxs[0]) == "pc" {
			logs.Warning(ctxs[0].Request.UserAgent())
			ctxs[0].SetSecureCookie(tools.JwtKey, "Authorization", i.Token, tools.LoginTimeout, "/")
		}
	}
}

func getRequestAgentType(ctx *context.Context) string {
	keywords := []string{"Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser"}
	for _, keyword := range keywords {
		if strings.Contains(ctx.Request.UserAgent(), keyword) {
			return "phone"
		}
	}
	return "pc"
}

// SignMD5Up MD5加密转大写
func SignMD5Up(data string) string {
	w := md5.New()
	io.WriteString(w, data)
	md5str2 := fmt.Sprintf("%x", w.Sum(nil))
	return strings.ToUpper(md5str2)
}
